package com.web.mqtt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.web.common.iot.mqtt.entity.MqttUser;
import com.web.common.iot.mqtt.entity.MqttUserEntity;
import com.web.common.password.PasswordEmitter;
import com.web.mqtt.entity.MqttUserExport;
import com.web.mqtt.mapper.MqttUserMapper;
import com.web.service.handler.error.CustomException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.web.common.result.R;
import com.web.common.result.ResultEnum;
import com.web.common.tool.DateTimeUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhouhui
 * @since 2024-01-05
 */
@Service
public class MqttUserServiceImpl extends ServiceImpl<MqttUserMapper, MqttUser> {
	
	private static final int PASSWORD_LENGTH = 12;
	
	/** 密码的加密方式   */
	private static final BCryptPasswordEncoder BCrypt = new BCryptPasswordEncoder();

	public R<IPage<MqttUserEntity>> getList(MqttUserEntity condition) {
		Page<MqttUser> page = new Page<>(condition.getPage(), condition.getSize());
		if(StringUtils.hasText(condition.getClientId())) {
			condition.setClientId("%" + condition.getClientId() + "%");
		}
		if(StringUtils.hasText(condition.getUsername())) {
			condition.setUsername("%" + condition.getUsername() + "%");
		}
		IPage<MqttUserEntity> dataList = this.baseMapper.getMqttUserList(page, condition);
		return R.ok(dataList);
	}
	
	/**
	 * 保存mqtt客户端信息
	 * 判断clientId是否存在，如果不存在进行新增
	 * @param mqttUser mqtt客户端信息
	 * @return R<Object> 密码明文
	 *
	 * @author zhouhui
	 * @since 2024.02.22 
	 */
	public R<Object> saveInfo(MqttUser mqttUser) {
		LambdaQueryWrapper<MqttUser> query = new LambdaQueryWrapper<>();
		query.eq(MqttUser::getClientId, mqttUser.getClientId());
		List<MqttUser> dataList = this.baseMapper.selectList(query);
		if(!dataList.isEmpty()) {
			throw new CustomException("客户端id已经存在");
		}
		
		String password = PasswordEmitter.getPassword(PASSWORD_LENGTH);
		mqttUser.setPassword(BCrypt.encode(password));
		mqttUser.setIsSuperuser(0);
		mqttUser.setOnline(0);
		mqttUser.setCreateTime(LocalDateTime.now());
		this.baseMapper.insert(mqttUser);
		
		//将密码的明文进行一次返回，进行展示记录
		mqttUser.setPassword(password);
		return R.ok(mqttUser);
	}
	
	/**
	 * 更新客户端信息，只能更新username
	 * @param mqttUser 需要更新的数据信息
	 * @return R<Object> 处理结果
	 *
	 * @author zhouhui
	 * @since 2024.02.22 
	 */
	public R<Object> updateInfo(MqttUser mqttUser) {
		LambdaUpdateWrapper<MqttUser> updateMqtt = new LambdaUpdateWrapper<>();
		updateMqtt.eq(MqttUser::getMainId, mqttUser.getMainId());
		updateMqtt.set(MqttUser::getUsername, mqttUser.getUsername());
		int updateRow = this.baseMapper.update(null, updateMqtt);
		if(updateRow <= 0) {
			throw new CustomException(ResultEnum.DATA_UPDATE_ERROR.getMessage());
		}
		return R.ok();
	}
	
	/**
	 * 删除客户端信息
	 * @param mqttUser 客户端信息
	 * @return R<Object> 处理结果
	 *
	 * @author zhouhui
	 * @since 2024.02.22 
	 */
	public R<Object> deleteInfo(MqttUser mqttUser) {
		int delRow = this.baseMapper.deleteById(mqttUser.getMainId());
		if(delRow <= 0) {
			throw new CustomException(ResultEnum.DATA_DELETE_ERROR.getMessage());
		}
		return R.ok();
	}
	
	 /**
	  * 重置客户端密码
	 * @param mqttUser 客户端信息
	 * @return R<MqttUser> 处理结果
	 *
	 * @author zhouhui
	 * @since 2024.02.22 
	 */
	public R<MqttUser> resetPassword(MqttUser mqttUser){
		String password = PasswordEmitter.getPassword(PASSWORD_LENGTH);
		
		LambdaUpdateWrapper<MqttUser> updateMqtt = new LambdaUpdateWrapper<>();
		updateMqtt.eq(MqttUser::getMainId, mqttUser.getMainId());
		updateMqtt.set(MqttUser::getPassword, BCrypt.encode(password));
		int updateRow = this.baseMapper.update(null, updateMqtt);
		if(updateRow <= 0) {
			throw new CustomException(ResultEnum.DATA_UPDATE_ERROR.getMessage());
		}
		
		mqttUser.setPassword(password);
		return R.ok(mqttUser);
	 }
	
	/**
	 * 导出mqtt客户端信息
	 * @param mqttUser 客户端信息
	 * @return List<MqttUserExport> 数据信息列表
	 *
	 * @author zhouhui
	 * @since 2024.02.22 
	 */
	public List<MqttUserExport> exportMqttUser(MqttUser condition){
		Page<MqttUser> page = new Page<>(1, -1);
		if(StringUtils.hasText(condition.getClientId())) {
			condition.setClientId("%" + condition.getClientId() + "%");
		}
		if(StringUtils.hasText(condition.getUsername())) {
			condition.setUsername("%" + condition.getUsername() + "%");
		}
		IPage<MqttUserEntity> result = this.baseMapper.getMqttUserList(page, condition);
		List<MqttUserEntity> dataList = result.getRecords();
		List<MqttUserExport> exportList = new ArrayList<>(dataList.size());
		for(MqttUserEntity item: dataList) {
			MqttUserExport exportItem = new MqttUserExport();
			exportItem.setClientId(item.getClientId());
			exportItem.setUsername(item.getUsername());
			exportItem.setCreateTime(item.getCreateTime().format(DateTimeFormatter.ofPattern(DateTimeUtil.YEAR_MONTH_DATE_TIME)));
			exportList.add(exportItem);
		}
		return exportList;
	}
}
